// 预约管理页面的JavaScript功能

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化预约管理功能
    initBookingManagement();
    
    // 初始化筛选功能
    initFilters();
    
    // 初始化表格交互
    initTableInteraction();
    
    // 初始化预约日历
    initBookingCalendar();
    
    // 添加动画效果
    addAnimationEffects();
});

// 初始化预约管理功能
function initBookingManagement() {
    console.log('预约管理功能初始化完成');
    
    // 设置页面标题
    document.title = '预约管理 - 图书馆管理系统';
}

// 初始化筛选功能
function initFilters() {
    // 获取所有筛选下拉框和日期选择器
    const filters = document.querySelectorAll('.filter-container select, .filter-container input[type="date"]');
    
    // 为每个筛选控件添加事件监听器
    filters.forEach(filter => {
        filter.addEventListener('change', function() {
            console.log('筛选条件变更:', this.name, this.value);
            // 模拟筛选操作
            simulateFiltering();
        });
    });
    
    // 高级筛选按钮事件
    const advancedFilterBtn = document.querySelector('.action-buttons .btn-primary');
    advancedFilterBtn.addEventListener('click', function() {
        showToast('高级筛选功能待实现');
    });
    
    // 模拟筛选操作
    function simulateFiltering() {
        // 显示加载动画
        showLoading();
        
        // 模拟网络请求延迟
        setTimeout(() => {
            hideLoading();
            // 这里应该是实际的表格数据更新逻辑
            showToast('筛选条件已应用');
        }, 500);
    }
}

// 初始化表格交互
function initTableInteraction() {
    // 获取表格元素
    const table = document.getElementById('bookingTable');
    const tbody = table.querySelector('tbody');
    const checkboxes = table.querySelectorAll('input[type="checkbox"]');
    
    // 全选/取消全选功能
    const headerCheckbox = table.querySelector('thead input[type="checkbox"]');
    headerCheckbox.addEventListener('change', function() {
        checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
    });
    
    // 操作按钮事件处理
    const actionButtons = table.querySelectorAll('.action-btn');
    actionButtons.forEach(button => {
        button.addEventListener('click', function() {
            const row = this.closest('tr');
            const bookingId = row.cells[1].textContent;
            
            if (this.classList.contains('view')) {
                viewBookingDetails(bookingId);
            } else if (this.classList.contains('edit')) {
                editBooking(bookingId);
            } else if (this.classList.contains('cancel')) {
                cancelBooking(bookingId);
            } else if (this.classList.contains('confirm')) {
                confirmBooking(bookingId);
            } else if (this.classList.contains('delete')) {
                deleteBooking(bookingId);
            }
        });
    });
    
    // 分页功能
    const paginationLinks = document.querySelectorAll('.pagination a');
    paginationLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            // 移除当前活动状态
            document.querySelectorAll('.pagination a.active').forEach(active => {
                active.classList.remove('active');
            });
            
            // 设置新的活动状态
            this.classList.add('active');
            
            // 模拟加载新页面数据
            showLoading();
            setTimeout(() => {
                hideLoading();
                showToast(`已切换到第${this.textContent}页`);
            }, 500);
        });
    });
}

// 查看预约详情
function viewBookingDetails(bookingId) {
    console.log('查看预约详情:', bookingId);
    // 模拟查看预约详情
    showToast(`查看预约 ${bookingId} 的详情`);
    // 实际项目中这里应该打开详情模态框
}

// 编辑预约
function editBooking(bookingId) {
    console.log('编辑预约:', bookingId);
    // 模拟编辑预约
    showToast(`编辑预约 ${bookingId}`);
    // 实际项目中这里应该打开编辑模态框
}

// 取消预约
function cancelBooking(bookingId) {
    console.log('取消预约:', bookingId);
    // 模拟取消确认
    if (confirm(`确定要取消预约 ${bookingId} 吗？`)) {
        showLoading();
        setTimeout(() => {
            hideLoading();
            showToast(`预约 ${bookingId} 已取消`);
            // 实际项目中这里应该更新DOM中的预约状态
            updateBookingStatus(bookingId, 'cancelled');
        }, 500);
    }
}

// 确认预约
function confirmBooking(bookingId) {
    console.log('确认预约:', bookingId);
    // 模拟确认操作
    showLoading();
    setTimeout(() => {
        hideLoading();
        showToast(`预约 ${bookingId} 已确认`);
        // 实际项目中这里应该更新DOM中的预约状态
        updateBookingStatus(bookingId, 'confirmed');
    }, 500);
}

// 删除预约
function deleteBooking(bookingId) {
    console.log('删除预约:', bookingId);
    // 模拟删除确认
    if (confirm(`确定要删除预约 ${bookingId} 吗？此操作不可恢复。`)) {
        showLoading();
        setTimeout(() => {
            hideLoading();
            showToast(`预约 ${bookingId} 已删除`);
            // 实际项目中这里应该从DOM中移除对应的行
        }, 500);
    }
}

// 更新预约状态
function updateBookingStatus(bookingId, status) {
    const tableRows = document.querySelectorAll('tbody tr');
    let statusText, statusClass;
    
    // 根据状态设置对应的文本和样式类
    switch(status) {
        case 'pending':
            statusText = '待确认';
            statusClass = 'pending';
            break;
        case 'confirmed':
            statusText = '已确认';
            statusClass = 'active';
            break;
        case 'cancelled':
            statusText = '已取消';
            statusClass = 'cancelled';
            break;
        case 'completed':
            statusText = '已完成';
            statusClass = 'completed';
            break;
        case 'overdue':
            statusText = '已逾期';
            statusClass = 'expired';
            break;
    }
    
    // 查找并更新对应的行
    tableRows.forEach(row => {
        if (row.cells[1].textContent === bookingId) {
            const statusCell = row.querySelector('.status');
            statusCell.textContent = statusText;
            statusCell.className = `status ${statusClass}`;
            
            // 根据状态更新操作按钮
            updateActionButtons(row, status);
        }
    });
}

// 更新操作按钮
function updateActionButtons(row, status) {
    const actionCell = row.cells[8];
    let buttonsHTML = '';
    
    // 根据不同状态显示不同的操作按钮
    switch(status) {
        case 'pending':
            buttonsHTML = `
                <button class="action-btn view">
                    <i class="fas fa-eye"></i>
                </button>
                <button class="action-btn edit">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="action-btn confirm">
                    <i class="fas fa-check"></i>
                </button>
            `;
            break;
        case 'confirmed':
            buttonsHTML = `
                <button class="action-btn view">
                    <i class="fas fa-eye"></i>
                </button>
                <button class="action-btn edit">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="action-btn cancel">
                    <i class="fas fa-times"></i>
                </button>
            `;
            break;
        case 'cancelled':
        case 'overdue':
            buttonsHTML = `
                <button class="action-btn view">
                    <i class="fas fa-eye"></i>
                </button>
                <button class="action-btn delete">
                    <i class="fas fa-trash"></i>
                </button>
            `;
            break;
        case 'completed':
            buttonsHTML = `
                <button class="action-btn view">
                    <i class="fas fa-eye"></i>
                </button>
            `;
            break;
    }
    
    // 更新操作按钮HTML
    actionCell.innerHTML = buttonsHTML;
    
    // 重新绑定事件监听器
    const newButtons = actionCell.querySelectorAll('.action-btn');
    newButtons.forEach(button => {
        button.addEventListener('click', function() {
            const bookingId = row.cells[1].textContent;
            
            if (this.classList.contains('view')) {
                viewBookingDetails(bookingId);
            } else if (this.classList.contains('edit')) {
                editBooking(bookingId);
            } else if (this.classList.contains('cancel')) {
                cancelBooking(bookingId);
            } else if (this.classList.contains('confirm')) {
                confirmBooking(bookingId);
            } else if (this.classList.contains('delete')) {
                deleteBooking(bookingId);
            }
        });
    });
}

// 初始化预约日历
function initBookingCalendar() {
    const calendarControls = document.querySelectorAll('.calendar-controls button');
    
    calendarControls.forEach(button => {
        button.addEventListener('click', function() {
            const currentMonth = document.querySelector('.calendar-controls span').textContent;
            console.log('切换月份:', this.querySelector('.fa-chevron-left') ? '上个月' : '下个月');
            
            // 显示加载动画
            showLoading();
            
            // 模拟加载日历数据
            setTimeout(() => {
                hideLoading();
                updateCalendar(this.querySelector('.fa-chevron-left') ? 'prev' : 'next');
            }, 800);
        });
    });
    
    // 初始化显示当前月份的预约日历
    updateCalendar('current');
}

// 更新日历显示
function updateCalendar(direction) {
    const calendarPlaceholder = document.querySelector('.calendar-placeholder');
    const currentMonthElement = document.querySelector('.calendar-controls span');
    
    // 模拟不同月份的预约数据
    const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
    const currentYear = 2023;
    let currentMonthIndex = 9; // 10月
    
    // 计算要显示的月份
    if (direction === 'prev') {
        currentMonthIndex = (currentMonthIndex - 1 + 12) % 12;
    } else if (direction === 'next') {
        currentMonthIndex = (currentMonthIndex + 1) % 12;
    }
    
    // 更新月份显示
    currentMonthElement.textContent = `${currentYear}年${months[currentMonthIndex]}`;
    
    // 模拟显示日历内容
    calendarPlaceholder.innerHTML = `
        <div class="calendar-grid">
            <div class="calendar-weekdays">
                <div>日</div>
                <div>一</div>
                <div>二</div>
                <div>三</div>
                <div>四</div>
                <div>五</div>
                <div>六</div>
            </div>
            <div class="calendar-days">
                ${generateCalendarDays(currentYear, currentMonthIndex + 1)}
            </div>
        </div>
        <div class="calendar-legend">
            <div class="legend-item">
                <span class="legend-color available"></span>
                <span>可预约</span>
            </div>
            <div class="legend-item">
                <span class="legend-color booked"></span>
                <span>已预约</span>
            </div>
            <div class="legend-item">
                <span class="legend-color full"></span>
                <span>已满</span>
            </div>
        </div>
    `;
}

// 生成日历天数据（模拟）
function generateCalendarDays(year, month) {
    // 获取该月第一天是星期几
    const firstDay = new Date(year, month - 1, 1).getDay();
    // 获取该月的天数
    const daysInMonth = new Date(year, month, 0).getDate();
    
    let daysHTML = '';
    
    // 添加上个月的占位天数
    for (let i = 0; i < firstDay; i++) {
        daysHTML += '<div class="calendar-day empty"></div>';
    }
    
    // 添加本月天数
    for (let day = 1; day <= daysInMonth; day++) {
        // 随机生成预约状态
        const status = Math.random() > 0.7 ? 'booked' : Math.random() > 0.9 ? 'full' : 'available';
        daysHTML += `<div class="calendar-day ${status}">${day}</div>`;
    }
    
    return daysHTML;
}

// 添加动画效果
function addAnimationEffects() {
    // 为统计卡片添加进入动画
    const statCards = document.querySelectorAll('.stat-card');
    statCards.forEach((card, index) => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(20px)';
        card.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
        
        setTimeout(() => {
            card.style.opacity = '1';
            card.style.transform = 'translateY(0)';
        }, 100 + 100 * index);
    });
    
    // 为表格行添加进入动画
    const tableRows = document.querySelectorAll('tbody tr');
    tableRows.forEach((row, index) => {
        row.style.opacity = '0';
        row.style.transform = 'translateY(20px)';
        row.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
        
        setTimeout(() => {
            row.style.opacity = '1';
            row.style.transform = 'translateY(0)';
        }, 200 + 100 * index);
    });
    
    // 为卡片添加进入动画
    const cards = document.querySelectorAll('.card');
    cards.forEach((card, index) => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(20px)';
        card.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
        
        setTimeout(() => {
            card.style.opacity = '1';
            card.style.transform = 'translateY(0)';
        }, 300 + 150 * index);
    });
}

// 显示加载动画
function showLoading() {
    // 检查是否已经存在加载元素
    let loadingOverlay = document.querySelector('.loading-overlay');
    
    if (!loadingOverlay) {
        loadingOverlay = document.createElement('div');
        loadingOverlay.className = 'loading-overlay';
        loadingOverlay.innerHTML = `
            <div class="loading-spinner">
                <div class="spinner"></div>
                <p>加载中...</p>
            </div>
        `;
        document.body.appendChild(loadingOverlay);
    }
    
    loadingOverlay.style.display = 'flex';
}

// 隐藏加载动画
function hideLoading() {
    const loadingOverlay = document.querySelector('.loading-overlay');
    if (loadingOverlay) {
        loadingOverlay.style.display = 'none';
    }
}

// 显示提示消息
function showToast(message) {
    // 检查是否已经存在toast元素
    let toast = document.querySelector('.toast');
    
    if (!toast) {
        toast = document.createElement('div');
        toast.className = 'toast';
        document.body.appendChild(toast);
    }
    
    // 设置消息内容
    toast.textContent = message;
    
    // 显示toast
    toast.classList.add('show');
    
    // 3秒后自动隐藏
    setTimeout(() => {
        toast.classList.remove('show');
    }, 3000);
}

// 导出预约数据
function exportBookingData() {
    console.log('导出预约数据');
    showLoading();
    
    // 模拟导出过程
    setTimeout(() => {
        hideLoading();
        showToast('预约数据导出成功');
    }, 1500);
}

// 批量取消预约
function batchCancelBookings() {
    const selectedCheckboxes = document.querySelectorAll('tbody input[type="checkbox"]:checked');
    
    if (selectedCheckboxes.length === 0) {
        showToast('请选择要取消的预约');
        return;
    }
    
    if (confirm(`确定要取消选中的 ${selectedCheckboxes.length} 个预约吗？`)) {
        showLoading();
        
        // 模拟取消过程
        setTimeout(() => {
            hideLoading();
            showToast(`已取消 ${selectedCheckboxes.length} 个预约`);
            // 实际项目中这里应该更新DOM中的预约状态
        }, 1000);
    }
}

// 批量确认预约
function batchConfirmBookings() {
    const selectedCheckboxes = document.querySelectorAll('tbody input[type="checkbox"]:checked');
    
    if (selectedCheckboxes.length === 0) {
        showToast('请选择要确认的预约');
        return;
    }
    
    showLoading();
    
    // 模拟确认过程
    setTimeout(() => {
        hideLoading();
        showToast(`已确认 ${selectedCheckboxes.length} 个预约`);
        // 实际项目中这里应该更新DOM中的预约状态
    }, 1000);
}

// 刷新预约数据
function refreshBookingData() {
    console.log('刷新预约数据');
    showLoading();
    
    // 模拟刷新过程
    setTimeout(() => {
        hideLoading();
        showToast('预约数据已刷新');
    }, 1000);
}

// 注册顶部操作按钮事件
const actionButtons = document.querySelectorAll('.action-buttons button');
actionButtons.forEach(button => {
    button.addEventListener('click', function() {
        if (this.querySelector('.fa-filter')) {
            showToast('高级筛选功能待实现');
        } else if (this.querySelector('.fa-download')) {
            exportBookingData();
        } else if (this.querySelector('.fa-refresh')) {
            refreshBookingData();
        }
    });
});

// 键盘快捷键支持
document.addEventListener('keydown', function(e) {
    // Ctrl+R 刷新数据
    if (e.ctrlKey && e.key === 'r') {
        e.preventDefault();
        refreshBookingData();
    }
    
    // Ctrl+E 导出数据
    if (e.ctrlKey && e.key === 'e') {
        e.preventDefault();
        exportBookingData();
    }
});

// 响应式布局调整
window.addEventListener('resize', function() {
    adjustTableLayout();
});

function adjustTableLayout() {
    const tableContainer = document.querySelector('.table-container');
    const table = document.getElementById('bookingTable');
    
    if (window.innerWidth < 768) {
        tableContainer.classList.add('scrollable');
    } else {
        tableContainer.classList.remove('scrollable');
    }
}

// 初始化表格布局
adjustTableLayout();

// 模拟实时数据更新
function simulateRealTimeUpdates() {
    setInterval(() => {
        const randomRow = Math.floor(Math.random() * document.querySelectorAll('tbody tr').length);
        const row = document.querySelectorAll('tbody tr')[randomRow];
        const statusCell = row.querySelector('.status');
        
        // 只对"待确认"的预约进行随机确认
        if (statusCell.classList.contains('pending') && Math.random() > 0.7) {
            const bookingId = row.cells[1].textContent;
            updateBookingStatus(bookingId, 'confirmed');
            showToast(`预约 ${bookingId} 已自动确认`);
        }
    }, 20000); // 每20秒模拟一次状态变化
}

// 启动实时数据更新模拟
simulateRealTimeUpdates();

// 提供导出CSV格式的函数
function exportToCSV() {
    // 模拟生成CSV数据
    let csvContent = '预约ID,用户,座位号,预约时间,结束时间,状态,操作时间\n';
    
    const tableRows = document.querySelectorAll('tbody tr');
    tableRows.forEach(row => {
        const cells = row.querySelectorAll('td');
        const rowData = [];
        
        // 收集表格数据（跳过复选框和操作列）
        for (let i = 1; i < cells.length - 1; i++) {
            let cellText = cells[i].textContent.trim();
            // 如果是状态列，提取文本内容
            if (cells[i].querySelector('.status')) {
                cellText = cells[i].querySelector('.status').textContent.trim();
            }
            rowData.push(`"${cellText}"`);
        }
        
        csvContent += rowData.join(',') + '\n';
    });
    
    // 创建下载链接
    const encodedUri = encodeURI("data:text/csv;charset=utf-8," + csvContent);
    const link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", `预约数据_${new Date().toISOString().slice(0, 10)}.csv`);
    document.body.appendChild(link);
    
    // 触发下载
    link.click();
    
    // 清理
    document.body.removeChild(link);
}

// 搜索功能
function initSearch() {
    const searchBox = document.querySelector('.search-box input');
    
    searchBox.addEventListener('input', function() {
        const searchTerm = this.value.toLowerCase();
        const tableRows = document.querySelectorAll('tbody tr');
        
        tableRows.forEach(row => {
            const bookingId = row.cells[1].textContent.toLowerCase();
            const user = row.cells[2].textContent.toLowerCase();
            const seatId = row.cells[3].textContent.toLowerCase();
            
            if (bookingId.includes(searchTerm) || user.includes(searchTerm) || seatId.includes(searchTerm)) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    });
}

// 初始化搜索功能
initSearch();

// 提供API: 可以被其他脚本调用的公共方法
export const BookingManagement = {
    refreshData: refreshBookingData,
    exportData: exportToCSV,
    batchCancel: batchCancelBookings,
    batchConfirm: batchConfirmBookings,
    getSelectedBookings: function() {
        const selectedCheckboxes = document.querySelectorAll('tbody input[type="checkbox"]:checked');
        const selectedBookings = [];
        
        selectedCheckboxes.forEach(checkbox => {
            const row = checkbox.closest('tr');
            selectedBookings.push(row.cells[1].textContent);
        });
        
        return selectedBookings;
    }
};